package com.sky.controller.Captcha;

import com.google.code.kaptcha.Producer;
import com.sky.redis.RedisCache;
import com.sky.result.AjaxResult;
import com.sky.result.Result;
import com.sky.service.ISysConfigService;
import com.sky.utils.Base64;
import com.sky.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/admin")
public class CaptchaController {
    @Resource(name="captchaProducer")
    private Producer captchaProducer;

    @Resource(name="captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysConfigService configService;


    @GetMapping("/captchaImage")
    public AjaxResult getCode(){
        AjaxResult ajax=AjaxResult.success();
        boolean captchaOnOff=true;
        if(!captchaOnOff){
            return ajax;
        }
        String uuid = IdUtils.simpleUUID();
        String verifyKey = "captcha_codes:" + uuid;
        String captchaType="math";
        String capStr = null, code = null;
        BufferedImage image=null;
        if("math".equals(captchaType)){
             String capText = captchaProducerMath.createText();
            code = capText.substring(capText.lastIndexOf("@") + 1);
             image=captchaProducerMath.createImage(capText);
        }
        redisCache.setCacheObject(verifyKey, code, 2, TimeUnit.MINUTES);

        FastByteArrayOutputStream os=new FastByteArrayOutputStream();
        try {
            ImageIO.write(image,"jpg",os);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        ajax.put("uuid",uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;


    }


}
